package com.qf.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.qf.aop.annocation.LoginUser;
import com.qf.consants.RabbitMQConstants;
import com.qf.entity.Car;
import com.qf.entity.Goods;
import com.qf.entity.User;
import com.qf.feign.api.IGoodsService;
import com.qf.resp.ResultEntity;
import com.qf.service.ICarService;
import com.qf.utils.JWTUitls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/carController")
public class CarController {

    @Autowired
    private ICarService carService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IGoodsService goodsService;


    @PostConstruct
    public void init() {
        redisTemplate.setKeySerializer(RedisSerializer.string());     // 把rediskey的序列化方式市值为字符串
    }

    // 先判断用户是否登录
    @RequestMapping("/addCar")
    @LoginUser // 表示这个方法需要当前登录的用户 ，如果登录就注入当前用户，没有注入null
    @ResponseBody
    public void addCar(Car car,
                       User user, @CookieValue(name = RabbitMQConstants.CAR_ANNO_NAME, required = false) String annoId, HttpServletResponse response) {

        Boolean result = false;
        if (user != null) {
            // 没有登录
            car.setUid(user.getId());
            car.setCreateTime(new Date());
            result = carService.insert(car);// 插入MySQL
        } else {

            // hset feidl(匿名用户ID) key(购买商品id) value(商品的数量)
            // hset  00000001 5 1
//                   00000001 2 2
//                   00000001 3 1
//                  00000002  10 2

            // 如果cookie中没有取到匿名用户Id才会创建匿名用户
            if (StringUtils.isEmpty(annoId)) {
                // 说明用户没有的登录，把购物车信息保存到redis中
                // 创建一个匿名用户的ID
                annoId = UUID.randomUUID().toString();

                // 创建一个Cookie
                Cookie cookie = new Cookie(RabbitMQConstants.CAR_ANNO_NAME, annoId);
                cookie.setMaxAge(60 * 60 * 24 * 7); // cookie保留七天i
                cookie.setPath("/"); // 解决cookie跨域的问题

                // 写入到浏览器中
                response.addCookie(cookie);
            }
            // 把购物车信息保存到redis中
            redisTemplate.opsForHash().put(annoId, car.getGid(), car.getCount());

            result = redisTemplate.opsForHash().hasKey(annoId, car.getGid());
        }

//        return ResultEntity.success(result);
    }

    @RequestMapping("/deleteCar")
    @ResponseBody
    public ResultEntity deleteCar(
            Car car, User user,
            @RequestHeader(name = RabbitMQConstants.SSO_LGOIN_TOKEN_NAME, required = false) String token) {
        System.out.println("car = [" + car + "], user = [" + user + "], token = [" + token + "]");
        if (user != null) {
            // 已经登录
        } else {
            // 未登录
        }

        return ResultEntity.success();
    }

    @RequestMapping("/getUserCarList")
    @LoginUser
    public String getUserCarList(User user,
                                 @CookieValue(name = RabbitMQConstants.CAR_ANNO_NAME, required = false) String annoId,
                                 ModelMap modelMap) {

        System.out.println(user);
        List<Car> carList = new ArrayList<>();

        if (user != null) {
            // 查询用户的购物车信息
            carList = carService.getUserCarList(user.getId());
        } else {
            carList = queryCarListByRedis(annoId);
        }

        modelMap.put("carList", carList);
        System.out.println(carList);
        return "carList";
    }

    public List<Car> queryCarListByRedis(String annoId) {
        if (!StringUtils.isEmpty(annoId)) {
            List<Car> carList = new ArrayList<>();
            // 根据feild获取key值
            Set gids = redisTemplate.opsForHash().keys(annoId);

            for (Object gid : gids) {
                // 根据field和key来获取value
                Object count = redisTemplate.opsForHash().get(annoId, gid);

                // 创建一个Car对象
                Car car = new Car();
                car.setCount((Integer) count);
                car.setGid((Integer) gid);
                car.setGoods(goodsService.getGoodsById((Integer) gid));

                // 添加到购物车集合
                carList.add(car);
            }
            return carList;
        }
        return null;
    }


//    @RequestMapping("/getCarListByAnnoId/{annoId}")
//    @ResponseBody
//    public List<Car> getCarListByAnnoId(@PathVariable String annoId) {
//        // 根据匿名用户Id查询购物车
//        return queryCarListByRedis(annoId);
//    }

    @RequestMapping("/mergeCar")
    @ResponseBody
    public void mergeCar(@RequestParam("annoId") String annoId, @RequestParam("userId") Integer userId) {
        System.out.println("annoId = [" + annoId + "], userId = [" + userId + "]");

        // 根据匿名用户Id查询购物车
        List<Car> carList = queryCarListByRedis(annoId);

        // 给购物车设置用户Id
        for (Car car : carList) {
            car.setUid(userId);
        }

        if (!carList.isEmpty()) {
            // 插入MySQL
            carService.insertBatch(carList);
        }

        // 清空redis中的购物车
        redisTemplate.delete(annoId);


    }

    @RequestMapping("/getCarListByUserId/{id}")
    @ResponseBody
    public List<Car> getCarListByUserId(@PathVariable("id") Integer id) {
        return carService.getUserCarList(id);
    }
}
